
const MongoClient = require('mongodb').MongoClient;
const  ObjectID = require('mongodb').ObjectID
const Config = require('./config')
class Db {
    // 使用单例 多次实例不共享的问题
    static getInstance() {
        if (!Db.instance) {
            Db.instance = new Db()
        }
        return Db.instance
    }
    constructor() {
        this.dbClient = null
    }
    connect() {
        return new Promise((resolve, reject) => {
            if (!this.dbClient) {
                MongoClient.connect(Config.dbUrl, (err, client) => {
                    if(err) {
                        reject(err)
                    }else {
                        var db = client.db(Config.dbName)
                        this.dbClient = db
                        resolve(this.dbClient)
                    }
                })
            }
            else resolve(this.dbClient)
        })
    }
    find(collectionName, json) {
        return new Promise((resolve, reject) => {
            this.connect().then((db) => {
                var result = db.collection(collectionName).find(json)
                result.toArray((err, docs) => {
                    if (err) reject(err)
                    resolve(docs)
                })
            })
        })
    }
    update(collectionName, json1, json2) {
        return new Promise((resolve, reject) => {
            this.connect().then(db => {
                db.collection(collectionName).updateOne(json1, {
                    $set: json2
                }, (err, result) => {
                    if(err) reject(err)
                    resolve(result)
                })
            })
        })
    }
    insert(collectionName, json) {
        return new Promise((resolve,  reject) => {
            this.connect().then((db) => {
                db.collection(collectionName).insertOne(json, (err, result) => {
                    if(err) reject(err)
                    resolve(result)
                })
            })
        })
    }
    remove(collectionName, json) {
        return new Promise((resolve,  reject) => {
            this.connect().then((db) => {
                db.collection(collectionName).removeOne(json, (err, result) => {
                    if(err) reject(err)
                    resolve(result)
                })
            })
        })
    }
    getObjectId(id) {
        return new ObjectID(id)
    }
}

module.exports = Db.getInstance()
